// 获取应用实例
const app = getApp();
const util = require("../../utils/util");
// 初始化数据库
const db = wx.cloud.database();
const imgs = db.collection("imgs");
const uimg = db.collection("uimg");

// pages/story/story.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: 1,
    zone: 1,
    fileList: [],
    fileId: "",
    upLoadDisabled: false,
    openid: "",
    isLoading: false,
    heartbeat_value: 0,

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
  },

  // 获取数据
  getImgsData(openid) {
    // wx.showLoading({
    //   title: "Loading...",
    // });
    this.setData({
      zone: 1
    })
    imgs.where({ _openid: openid }).get({
      success: (res) => {
        if (res.data.length == 0) {
          imgs.add({
            data: {
              myImgs: [],
            },
            success: () => {
              wx.stopPullDownRefresh();
              wx.hideLoading();
            },
            fail: (err) => {
              wx.showToast({
                title: "初始化失败",
                icon: "error",
              });
            },
            complete: () => {
              wx.stopPullDownRefresh();
              wx.hideLoading();
            },
          });
        } else {
          wx.stopPullDownRefresh();

          this.setData({
            fileList: res.data[0].myImgs,
            upLoadDisabled: false,
            isLoading: false,
          });

          wx.hideLoading();
        }
      },
      fail: () => {
        wx.showToast({
          title: "获取失败",
          icon: "none",
        });
      },
      complete: () => {
        wx.stopPullDownRefresh();
        wx.hideLoading();
      },
    });
  },

  // chooseMedia() {
  //   const that = this;
  //   wx.chooseMedia({
  //     count: 1,
  //     mediaType: ['image', 'video'],
  //     sourceType: ['album', 'camera'],
  //     maxDuration: 30,
  //     camera: 'back',
  //     success(res) {
  //       console.log(res.tempFiles[0].tempFilePath);
  //       const { tempFilePath } = res.tempFiles[0];
  //       that.setData({
  //         upLoadDisabled: true,
  //       });
  //       that.uploadImage(tempFilePath);

  //       // util.subscribe(2, "测试", false);
  //     }
  //   })
  // },

  addImgsData(openid, imgurl, fileId) {
    const that = this;
    const { fileList, heartbeat_value } = that.data;
    fileList.push({
      url: imgurl,
      fileId,
      time: +new Date(),
    });
    imgs.where({ _openid: openid }).update({
      data: {
        myImgs: fileList,
      },
      success: function (res) {
        wx.showToast({
          title: "上传成功",
          icon: "success",
        });
      },
      fail: () => {
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
      complete: () => {
        that.getImgsData(openid);
        wx.hideLoading();
      },
    });
    uimg.where({ _openid: openid }).get({
      success: res => {
        let heartbeat_value = res.data[0].heartbeat_value;
        heartbeat_value += 2;
        uimg.where({ _openid: openid }).update({
          data: { heartbeat_value },
          success: (res) => { },
          fail: (err) => {
            console.log(err);
          }
        })
      }
    })
  },

  // 添加图片
  afterRead(e) {
    const that = this;
    const { file } = e.detail;
    // console.log(file);
    that.setData({
      upLoadDisabled: true,
    });
    that.uploadImage(file.url);
  },

  // 上传到云储存
  uploadImage(fileURL) {
    var that = this;
    wx.showLoading({
      title: "上传中",
      mask: true,
    });
    wx.cloud.uploadFile({
      cloudPath: "story/story" + new Date().getTime() + ".png", // 上传至云端的路径
      filePath: fileURL, // 小程序临时文件路径
      success: (res) => {
        //获取图片的http路径，准备添加到数据库中
        // console.log(res.fileID);
        that.addImagePath(res.fileID);
        that.setData({
          fileID: res.fileID,
        });
      },
      fail: () => {
        that.setData({
          upLoadDisabled: false,
        });
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
    });
  },

  // 获取图片上传后的url路径
  addImagePath(fileId) {
    const openid = wx.getStorageSync("openid");
    // console.log(fileId);
    var that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileId],
      success: (res) => {
        const url = res.fileList[0].tempFileURL;
        that.addImgsData(openid, url, fileId);
      },
      fail: () => {
        that.setData({
          upLoadDisabled: false,
        });
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
    });
  },

  // 删除对应图片
  delImg(e) {
    const that = this;
    let { openid, fileList } = that.data;
    const { time, fileid } = e.currentTarget.dataset;
    wx.showModal({
      title: "确认删除",
      content: "请问您想好要删除该图片了嘛？一经删除不可恢复",
      success: (result) => {
        if (result.confirm) {
          fileList = fileList.filter((i) => i.time != time);
          imgs.where({ _openid: openid }).update({
            data: {
              myImgs: fileList,
            },
            success: function (res) {
              wx.showToast({
                title: "删除成功",
                icon: "success",
              });
              that.getImgsData(openid);

              wx.cloud.deleteFile({
                fileList: [fileid],
                success(res) {
                  console.log(res, "删除文件");
                },
                fail(err) {
                  console.log(err);
                },
              });
            },
            fail: () => {
              wx.showToast({
                title: "删除失败",
                icon: "error",
              });
            },
          });
        }
      },
      fail: () => { },
      complete: () => { },
    });
  },

  shareImg(e) {
    const current = e.currentTarget.dataset.url;
    wx.showLoading({
      title: '加载中...',
    })
    wx.downloadFile({
      url: current,
      success: (res) => {
        wx.hideLoading();
        wx.showShareImageMenu({
          path: res.tempFilePath,
          style: 'v2',
          needShowEntrance: true,
          entrancePath: 'pages/login/login',
        })
      }
    })
  },
  // 图片预览
  clickPreview(e) {
    const { fileList } = this.data;
    const current = e.currentTarget.dataset.url;
    const urls = fileList.map((v) => v.url);
    wx.previewImage({
      current, // 当前显示图片的 http 链接
      urls, // 需要预览的图片 http 链接列表
    });
  },

  changeStory() {
    const that = this;
    const { openid, zone } = that.data;

    if (zone == 1) {
      wx.showModal({
        title: '相册切换',
        content: '是否查看对方相册',
        complete: (res) => {
          if (res.cancel) { }

          if (res.confirm) {
            wx.showLoading({
              title: "切换中...",
              mask: true,
            });
            uimg.where({ _openid: openid }).get({
              success: (res) => {
                if (res.data[0].o_openid) {
                  const o_openid = res.data[0].o_openid;
                  const heartbeat_value = res.data[0].heartbeat_value;
                  that.setData({
                    o_openid,
                    heartbeat_value
                  });
                  imgs.where({ _openid: o_openid }).get({
                    success: (result) => {
                      that.setData({
                        fileList: result.data[0].myImgs,
                        zone: 2,
                      });
                    },
                    fail: () => {
                      wx.showToast({
                        title: "切换失败",
                        icon: "none",
                      });
                    },
                    complete: () => {
                      wx.hideLoading();
                    },
                  });
                } else {
                  wx.hideLoading();
                  wx.showModal({
                    title: "操作提醒",
                    content:
                      "你还没有绑定情侣，绑定后即可查看对方相册，如现在绑定请点击确定，不绑定请点击取消",
                    confirmColor: "#a5646d",
                    success: (result) => {
                      if (result.confirm) {
                        wx.navigateTo({
                          url: "/packageMine/pages/invitecode/invitecode",
                          success: (result) => { },
                          fail: () => { },
                          complete: () => { },
                        });
                      }
                    },
                    fail: () => { },
                    complete: () => { },
                  });
                }
                // console.log(res.data[0].o_openid);
              },
              fail: () => {
                wx.hideLoading();
                wx.showToast({
                  title: "切换失败",
                  icon: "none",
                });
              },
            });
          }
        }
      })
    } else {
      wx.showLoading({
        title: "切换中...",
        mask: true,
      });
      that.getImgsData(openid);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const openid = wx.getStorageSync("openid");
    this.setData({
      openid,
    });
    wx.showLoading({
      title: "Loading...",
      mask: "true",
    });
    this.getImgsData(openid);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const openid = wx.getStorageSync("openid");
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2,
        theme: app.globalData.theme,
      });
    }
    this.setData({
      theme: app.globalData.theme,
      openid,
    });
    const { theme } = this.data
    if (theme == 1) {
      wx.setTabBarStyle({
        backgroundColor: '#a5646d',
      })
    } else if (theme == 2) {
      wx.setTabBarStyle({
        backgroundColor: '#1a1a1a',
      })
    } else if (theme == 3) {
      wx.setTabBarStyle({
        backgroundColor: '#86C6F6',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const { openid } = this.data;
    this.setData({
      isLoading: true,
    });
    wx.showLoading({
      title: "Loading...",
      mask: "true",
    });
    this.getImgsData(openid);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
